<?php
/**
 * @link https://www.kancloud.cn/cleverstone/ymb2
 * @copyright Copyright (c) 2020 Yii Manager Software LLC
 */

namespace common\helper;

use yii\base\BaseObject;

/**
 * 结果对象化
 */
final class ResultObject extends BaseObject
{
    /**
     * @var string|null 错误消息
     */
    public $error;
    /**
     * @var array|mixed 数据结果
     */
    public $result = [];
    /**
     * @var array|mixed 额外字段
     */
    public $extra = [];

    /**
     * 实例化结果
     * @param array $props 属性初始化
     * @return $this
     */
    public static function create(array $props = [])
    {
        return new self($props);
    }

    /**
     * 是否存在错误
     * @return bool
     */
    public function hasError()
    {
        return isset($this->error);
    }

    /**
     * 当结果存在错误时，抛出异常
     * @return void
     * @throws \Exception
     */
    public function throwExceptionWhenHasError()
    {
        if (isset($this->error)) {
            throw new \Exception($this->error ?: 'Unknown Error。');
        }
    }
}